<template>
	<div>
    <el-tabs v-model="state.activeName"  @tab-change="handleClick">
      <el-tab-pane label="列表" name="list">
        <zh-space>
				<zh-card title="">
					<zh-form ref="queryForm" :model="state.queryParam">
						<zh-form-select
							v-model="state.queryParam.searchType"
							label="查询类型"
							:options="state.searchTypeData"
							prop="searchType"
							placeholder="默认查询未授权组织"
							@change="searchTypeChange"
						>
						</zh-form-select>
						<zh-form-input label="组织名称" v-model="state.queryParam.fullName" prop="orgName" placeholder="支持模糊查询" />
						<template v-if="state.advanced">
              <zh-form-select placeholder="请搜索后选择上级组织"
                funcCode="org0001"
                label="上级组织"
                prop="parentId"
                searchField="orgName"
                :fieldNames="{
                  label: 'orgName',
                  value: 'orgId',
                }"
                :lazy="true"
                v-model="state.queryParam.parentId">
              </zh-form-select>
							<zh-form-input prop="creditCode" label="社会信用码" placeholder="" v-model="state.queryParam.creditCode"></zh-form-input>
              <zh-form-cascader
                prop="orgType"
                label="组织类型"
                placeholder="请选择"
                :props="{ label: 'title', leaf: 'isLeaf', treeList: 'treeList', emitPath: false }"
                v-model="state.queryParam.orgType"
                :options="state.orgTypeSelectTreeData"
              ></zh-form-cascader>
              <zh-form-select
                prop="orgPro"
                label="组织性质"
                :options="state.dictData.orgPro"
                placeholder="请选择"
                v-model="state.queryParam.orgPro"
              ></zh-form-select>
              <zh-form-select placeholder="请搜索后选择主管单位"
                funcCode="org0001"
                label="主管单位"
                prop="mainDeptId"
                searchField="orgName"
                :fieldNames="{
                  label: 'orgName',
                  value: 'orgId',
                }"
                :lazy="true"
                v-model="state.queryParam.mainDeptId">
              </zh-form-select>

            </template>
						<zh-form-query v-model="state.advanced" :formRef="queryForm"  :tableRef="orgListTable"></zh-form-query>
					</zh-form>
				</zh-card>
				<zh-table
					ref="orgListTable"
					:columns="state.tableColumn"
					:funcCode="state.funcCode"
					:disabled="false"
					highlight-current-row
					:loading="state.orgLoading"
					:checkbox-config="{ trigger: 'row' }"
				>
					<template #status_default="{ row }">
						<zh-badge :status="statusMap[row.status].status" :text="statusMap[row.status].text" />
					</template>
				</zh-table>
			</zh-space>
      </el-tab-pane>
      <el-tab-pane label="树" name="tree"><OrgTreeForm ref="orgTreeRef" :type="type" :id="id"/></el-tab-pane>
    </el-tabs>
    
  </div>
</template>
<script lang="ts" setup name="orgModule">
import OrgTreeForm from '@/views/system/component/OrgTreeForm.vue';
//------------------接收传入参数(组件)-------------------
const statusMap = {
	0: {
		status: 'error',
		text: '禁用',
	},
	1: {
		status: 'processing',
		text: '启用',
	},
};
const props = defineProps({
	id: {
		type: String,
	},
	type: {
		type: String,
	},
});
//------------------定义子组件---------------------------
const queryForm = ref();
const orgListTable = ref();
const orgTreeRef = ref();
//------------------内部变量定义-------------------------
const state = reactive({
  advanced:true,
  activeName:'list',
	dictData: {} as any,
	orgTypeSelectTreeData: [],
	areaCodeSelectTreeData: [],
	queryParam: {searchType:'1'} as any,
  searchTypeData: [
		{ dictKey: '1', dictValue: '从未授权' },
		{ dictKey: '2', dictValue: '已授权' },
		{ dictKey: '3', dictValue: '全部' },
	],
  tableColumn:[
    { type: 'checkbox', width: 50, fixed: 'left' },
		{ type: 'seq', width: 50, fixed: 'left', align: 'center', title: '序号' },
		{ field: 'orgId', title: '组织Id', visible: false, fixed: 'left', align: 'center', width: 150 },
		{ field: 'orgName', title: '组织名称', align: 'center', fixed: 'left', minWidth: 200 },
    { field: 'orgTypeName', title: '组织类型', align: 'center', width: 150 },
    { field: 'status', title: '有效状态', align: 'center', width: 150,
      slots: {
				default: 'status_default',
			}, },
    { field: 'parentName', title: '上级组织名称', align: 'center', width: 200 },
    { field: 'mainDeptName', title: '主管单位', align: 'center', width: 200 },
    { field: 'orgProName', title: '单位性质', align: 'center', width: 200 },
    { field: 'creditCode', title: '统一社会信用代码', align: 'center', width: 200 },
    { field: 'areaCode', title: '行政区划', align: 'center', width: 200 },
    { field: 'parentPath', title: '全路径', align: 'center', width: 500 },
	],
  funcCode:'',
  orgLoading:false,
});
//------------------定义调用方法-------------------------
const emit = defineEmits(['searchTypeBtn','activeNameChange']);
const handleClick=(name)=>{
  emit('activeNameChange', name);
  if(name==='tree'){
    orgTreeRef.value.findOrgTreeList();
  }else if(name==='list'){
    onOrgQuery();
  }
}
//组织列表查询
const onOrgQuery = () => {
  if (props.id) {
    orgListTable.value.query(state.queryParam);
  }
};
function getCheckedIds() {
	const checkedList = orgListTable.value.getAllCheckboxRecords();
	if (checkedList) {
		if (checkedList.length <= 0) {
			$messageBox.warning('请先勾选需要操作的组织', '提示');
			return false;
		}
	} else {
		$messageBox.warning('请先勾选需要操作的组织', '提示');
		return false;
	}
	let orgIds: any = [] ;
	checkedList.forEach((item: any) => {
		orgIds.push(item.orgId);
	});
	return orgIds;
}
const save=()=>{
  if (!props.id) {
    if (props.type === 'role') {
			$messageBox.warning('请先传入角色id', '提示');
			return false;
    }else{
      $messageBox.warning('请先传入用户id', '提示');
      return false;
    }
	}
  //保存组织授权
  orgTreeRef.value.saveOrg();
}
const add=()=>{
  if (!props.id) {
    if (props.type === 'role') {
			$messageBox.warning('请先传入角色id', '提示');
			return false;
    }else{
      $messageBox.warning('请先传入用户id', '提示');
      return false;
    }
	}
  //保存组织授权
  const orgIds = getCheckedIds();
  if (!orgIds||orgIds.length<=0) {
		$messageBox.warning('请先传勾选组织信息', '提示');
		return false;
  }
  let params={orgIds:orgIds} as any
  let funcCode="";
  if (props.type === 'role') {
			params.roleId=props.id
      funcCode = 'role0016';
	} else if (props.type === 'user') {
			params.userId=props.id
			funcCode = 'user0032';
	}
  $api.common.send.post(funcCode, params).then(() => {
		$messageBox.success('关联成功', '成功提示');
		onOrgQuery();
	}).catch(() => {});
}
const del=()=>{
  if (!props.id) {
    if (props.type === 'role') {
			$messageBox.warning('请先传入角色id', '提示');
			return false;
    }else{
      $messageBox.warning('请先传入用户id', '提示');
      return false;
    }
	}
  //解除组织授权
  const orgIds = getCheckedIds();
  if (!orgIds||orgIds.length<=0) {
		$messageBox.warning('请先传勾选组织信息', '提示');
		return false;
  }
  let params={orgIds:orgIds} as any
  let funcCode="";
  if (props.type === 'role') {
			params.roleId=props.id
      funcCode = 'role0017';
	} else if (props.type === 'user') {
			params.userId=props.id
			funcCode = 'user0033';
	}
  $api.common.send.post(funcCode, params).then(() => {
		$messageBox.success('取消关联成功', '成功提示');
		onOrgQuery();
	}).catch(() => {});
}
function searchTypeChange(value) {
	onOrgQuery();
	emit('searchTypeBtn', value);
	setTimeout(() => {
		// state.userChecked = []
		orgListTable.value.clearCheckboxRow();
		orgListTable.value.clearCheckboxReserve();
	}, 50);
}
//------------------初始化------------------------------
onBeforeMount(() => {
	if (props.type === 'role') {
		state.queryParam.roleId = props.id;
		state.funcCode = 'role0015';
	} else if (props.type === 'user') {
		state.queryParam.userId = props.id;
		state.funcCode = 'user0031';
	}
});
onMounted(()=>{
 
  // 数据初始化
  const params = {
    dictFields: 'orgPro',
  };
  $api.common.getBatchDict.post( params).then((res) => {
    state.dictData = res.result;
  });
  const paramsTree = {
    dictField: 'orgType',
  };
  $api.common.send.post('dict0025', paramsTree).then((res) => {
    state.orgTypeSelectTreeData = res.result;
  });
  nextTick(()=>{
    onOrgQuery();
  })
})
//--------------------监听变动数据-----------------------------
watch(
	() => props.id,
	(id) => {
		if (id) {
			state.queryParam[props.type + 'Id'] = id;
		}
	}
);
//------------设置给父组件调用的数据/方法(组件)-----------
defineExpose({
	onOrgQuery,
  add,
	save,
	del
});
</script>
<style lang="scss" scoped></style>
